package com.dayuanit.dy17.atm.controller;

import com.alibaba.excel.EasyExcel;
import com.dayuanit.dy17.atm.dto.FlowDTO;
import com.dayuanit.dy17.atm.service.IFlowService;
import com.dayuanit.dy17.atm.util.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FlowController extends BaseController {

    @Autowired
    private IFlowService flowService;

    /**
     * 处理CSV格式
     * @param response
     * @param cardId
     * @param password
     */
    private void processCSVFile(HttpServletResponse response,
                                long cardId,
                                String password) {
        int currentPage = 1;
        PageHelper<List<FlowDTO>> pageHelper = null;
        BufferedWriter bw = null;

        try {
            //输出表头
            bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            //卡号，金额，备注，日期
            String tableTitle = "卡号,金额,备注,时间";
            bw.write(tableTitle);
            bw.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //模拟分页，一页一页的查询，并输出给客户端
        do {

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            pageHelper = flowService.loadFlows(cardId, password, currentPage ++);

            List<FlowDTO> flowDTOS = pageHelper.getPageData();
            String cardNum = flowDTOS.get(0).getCardNum();

            response.setContentType("application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename="+cardNum+".csv");

            try {
                for (FlowDTO flow : flowDTOS) {
                    String msg = flow.getCardNum() + "," + flow.getAmount() + "," + flow.getRemark() + "," + flow.getCreateTime();
                    bw.write(msg);
                    bw.newLine();
                    bw.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } while (pageHelper != null && pageHelper.getTotalPage() >= currentPage);
    }

    /**
     * 处理Excel格式
     * @param response
     * @param cardId
     * @param password
     */
    private void processExcelFile(HttpServletResponse response,
                              long cardId,
                              String password) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            int currentPage = 1;
            PageHelper<List<FlowDTO>> pageHelper = null;
            List<FlowDTO> flowDatas = new ArrayList<>();

            // 得到导出的数据
            do {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                pageHelper = flowService.loadFlows(cardId, password, currentPage++);

                List<FlowDTO> flowDTOS = pageHelper.getPageData();
                flowDatas.addAll(flowDTOS);
            } while (pageHelper != null && pageHelper.getTotalPage() >= currentPage);

            EasyExcel.write(response.getOutputStream(), FlowDTO.class).sheet("模板").doWrite(flowDatas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出流水
     * @param fileType 1-CSV格式  2-Excel格式 3-XML格式 4-JSON格式
     * @param cardId
     * @param password
     * @param response
     */
    @RequestMapping(value = "/flow/downLoadFLows")
    @ResponseBody
    public void downLoadFLows(@RequestParam(required = false, defaultValue = "1") int fileType,
                              long cardId,
                              String password,
                              HttpServletResponse response) {

        if (1 == fileType) {
            processCSVFile(response, cardId, password);
        }

        if (2 == fileType) {
            processExcelFile(response, cardId, password);
        }
    }
}
